/*
 * Copyright (C) 2009 Dimitrios C. Michalakos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.cs.util.http;

import com.cs.util.binary.Base64;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * AuthBasicHeader can be used for parsing a HTTP Authorization Header of type BASIC.
 * @author dimitris@jmike.gr
 */
public class AuthBasicHeader {

    private String username = null;
    private String password = null;

    /**
     * Parses the specified authorization header and constructs a new instance of AuthBasicHeader.
     * @param auth64 The authorization header as provided in the HTML envelope.
     */
    public AuthBasicHeader(String auth64) {
        if (isBasicAuthType(auth64)) {
            try {
                final String[] s = (new String(Base64.decode(auth64.substring(6)), "UTF-8")).split(":", 2);//decode the header and split it on ':'
                this.username = s[0];
                this.password = s[1];
            } catch (UnsupportedEncodingException ex) {
                /* ignore the exception */
            } catch (IOException ex) {
                /* ignore the exception */
            }
        }
    }

    /**
     * Returns true if authentication scheme is BASIC.
     * @param auth The authorization header as provided in the HTML envelope.
     * @param auth
     * @return
     */
    private Boolean isBasicAuthType(String auth) {
        if (auth == null) {
            return false;
        }
        if (auth.toLowerCase().startsWith("basic")) {
            return true;
        }
        return false;
    }

    /**
     * Returns the username contained in the authorization header.
     * If authorization schema is not BASIC or authorization header does not exist, null value is returned.
     * @return
     */
    public String getUserName() {
        return username;
    }

    /**
     * Returns the password contained in the authorization header.
     * If authorization schema is not BASIC or authorization header does not exist, null value is returned.
     * @return
     */
    public String getPassword() {
        return password;
    }

    public static void main(String[] args) {
        AuthBasicHeader auth = new AuthBasicHeader("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
        System.out.println(auth.getUserName());
        System.out.println(auth.getPassword());
    }
}
